#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include "Logger.hpp"
#include "Comm.hpp"

static const uint16_t gdefaultsockfd = -1;
static const int gbacklog = 8;
static const int gport = 8080;
class TcpEchoServer
{
public:
    TcpEchoServer(uint16_t port = gport) : _listensockfd(gdefaultsockfd), _port(port)
    {
    }
    void Init()
    {
        // 1.创建套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0); // tcp
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "create tcp socket error";
            exit(SOCK_CREATE_ERROR);
        }
        LOG(LogLevel::INFO) << "create tcp socket success: " << _listensockfd;

        // 2.bind套接字
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(_listensockfd, (struct sockaddr *)&local, sizeof(local) != 0))
        {
            LOG(LogLevel::FATAL) << "bind socker error";
            exit(SOCK_BINd_ERROR);
        }
        LOG(LogLevel::INFO) << "bind socker success: " << _listensockfd;

        // 3.listen套接字
        if (listen(_listensockfd, gbacklog) != 0) // tcp
        {
            LOG(LogLevel::FATAL) << "listen socket error";
            exit(SOCK_LISTEN_ERROR);
        }
        LOG(LogLevel::INFO) << "listen socket success: " << _listensockfd;
    }

    void Start()
    {
        while (true)
        {
            struct sockaddr_in peer;
            bzero(&peer, sizeof(peer));
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensockfd, (struct sockaddr *)&peer, &len);
            if(sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept client error";
                continue;
            }
            LOG(LogLevel::INFO) << "获取新链接成功" << sockfd;
            
        }
    }
    ~TcpEchoServer()
    {
    }

private:
    int _listensockfd;
    int _port;
};